<template>
  <div class="page flex flex-rc pt-50 pb-70">
    <div class="flex flex-col flex-rb" style="width: 80%">
      <div class="flex flex-rc fz-40 fw-bold ls">{{ $t('注册') }}</div>

      <div>
        <!-- 上级邀请码 -->
        <van-field
          class="mb-15"
          :border="false"
          :placeholder="$t('请输入上级邀请码')"
          v-model="inviteId"
        ></van-field>

        <!-- 注册按钮 -->
        <van-button
          style="height: 45px"
          color="linear-gradient(to right, #0eb78e, #4573a4, #7735b8)"
          block
          @click="register"
        >
          <div class="fz-17 cl-black fw-bold ls">{{ $t('注册') }}</div>
        </van-button>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { showSuccess, showError, showLoading } from 'js/utils'

const router = useRouter()
const route = useRoute()

const inviteId = ref(route.query.inviteId || '')
const loading = ref(null)

// 注册
async function register() {
  try {
    loading.value = showLoading()
    await bindParentAddress()
    loading.value?.close()
    router.replace('/')
  } catch (err) {
    loading.value?.close()
  }
}

// 绑定上级地址
function bindParentAddress() {
  return new Promise(async (resolve, reject) => {
    try {
      const parentAddress = inviteId.value || defaultParentAddress
      console.log('绑定上级地址')
      await userContract.context.methods.referParent(parentAddress).send({
        from: fromAddress,
      })
      showSuccess($t('注册成功'))
      console.log(`绑定上级地址成功：${parentAddress}`)
      resolve(parentAddress)
    } catch (err) {
      showError($t('注册失败'))
      console.error('绑定上级地址失败')
      console.error(err)
      reject(err)
    }
  })
}
</script>

<style lang="scss" scoped>
.page {
  background: url('../assets/img/register/bg.png') no-repeat center / cover;
}
</style>
